package edu.njust.httpmanager.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import edu.njust.httpmanager.common.Result;
import edu.njust.httpmanager.entity.User;
import edu.njust.httpmanager.mapper.UserMapper;
import edu.njust.httpmanager.service.IUserService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Resource
    private UserMapper userMapper;

    /**
     * 盐值，混淆密码
     */
    private static final String SALT = "kirby";

    @Override
    public User queryUser(User user) {

        // 不能明文存储密码，比照的是加密后的密码
        String encryptPassword = DigestUtils.md5DigestAsHex((SALT + user.getPassword()).getBytes());
        user.setPassword(encryptPassword);

        LambdaQueryWrapper<User> userWrapper = new LambdaQueryWrapper<>();

        // 创建查询条件
        userWrapper.eq(User::getAccount, user.getAccount())
                .eq(User::getPassword, user.getPassword());

        return userMapper.selectOne(userWrapper);
    }

    @Override
    public Result<?> register(User user) {
        if (user.getPassword().length() < 8) {
            return Result.error("密码长度小于八位");
        }

        // 判断账号是否已被注册、邮箱是否已经绑定账号、密码保存前需要加密
        if (userMapper.selectOne(new LambdaQueryWrapper<User>().eq(User::getAccount, user.getAccount())) != null) {
            return Result.error("账号已被占用");
        }
        if (userMapper.selectOne(new LambdaQueryWrapper<User>().eq(User::getEmail, user.getEmail())) != null) {
            return Result.error("当前邮箱已绑定其它账号");
        }

        // 加密密码
        String encryptPassword = DigestUtils.md5DigestAsHex((SALT + user.getPassword()).getBytes());
        user.setPassword(encryptPassword);

        // 保存用户
        if (!this.save(user)) {
            return Result.error("数据库错误，注册失败");
        }

        return Result.success("注册成功");
    }

}
